package com.yt.order.api.client;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.yt.common.constant.Result;
import com.yt.common.enums.CodeEnum;
import com.yt.order.models.bo.WorkOrderCompleteBO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import com.yt.order.models.service.IWorkOrderInfoService;
import com.yt.order.models.bo.WorkOrderInfoBO;
import com.yt.order.models.bo.WorkOrderInfoSaveBO;
import com.yt.order.models.dto.WorkOrderInfoDTO;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 工单信息控制器
 *
 * @author yzz
 * @Date 2025-09-03 14:18:55
 */

@RestController
@RequestMapping("/api/workOrderInfo")
@Slf4j
@Api(value = "WorkOrderInfoApiController",tags = "工单信息Api接口")
public class WorkOrderInfoApiController {

    @DubboReference
    private IWorkOrderInfoService workOrderInfoService;

    @PostMapping("/get")
    @ApiOperation(value = "根据id查找",notes = "根据id查找")
    @ApiImplicitParam(name = "id",value = "id",required = true,paramType = "query", dataType = "Long")
    public Result<WorkOrderInfoDTO> get(@RequestParam("id") Long id){
        if(id == null){
            return new Result<>(CodeEnum.FAIL_100002 );
        }

        WorkOrderInfoDTO dto = workOrderInfoService.selectById(id);

        return new Result<>(dto);
    }

    @ApiOperation(value = "工单信息列表",notes = "工单信息列表")
    @PostMapping("/queryPageList")
    public Result<Page<WorkOrderInfoDTO>> queryPageList(WorkOrderInfoBO bo){
        Wrapper<WorkOrderInfoDTO> wrapper = new EntityWrapper<>();
                if (bo.getStatus() != null){
                    wrapper.eq("status", bo.getStatus());
                }
        if (bo.getStartDate() != null){
            wrapper.ge("create_time", bo.getStartDate());
        }
        if (bo.getEndDate() != null){
            wrapper.le("create_time", bo.getEndDate());

        }
        Page<WorkOrderInfoDTO> page = new Page<>(bo.getPageNo(), bo.getPageSize());
        page = workOrderInfoService.selectPage(page, wrapper);

        return new Result<>(page);
    }

    @ApiOperation(value = "获取所有工单信息", notes = "获取所有工单信息")
    @PostMapping("/listAll")
    public Result<List<WorkOrderInfoDTO>> listAll() {
        List<WorkOrderInfoDTO> workOrderList = workOrderInfoService.selectList(new EntityWrapper<>());
        return new Result<>(workOrderList);
    }
    
    @ApiOperation(value = "根据客户ID获取工单信息", notes = "根据客户ID获取工单信息")
    @PostMapping("/getByCustomerId")
    @ApiImplicitParam(name = "customerId", value = "客户ID", required = true, paramType = "query", dataType = "Long")
    public Result<List<WorkOrderInfoDTO>> getByCustomerId(@RequestParam("customerId") Long customerId) {
        log.info("开始根据客户ID获取工单信息，客户ID: {}", customerId);
        
        if (customerId == null) {
            log.warn("查询失败，客户ID为空");
            return new Result<>(CodeEnum.FAIL_100002);
        }
        
        List<WorkOrderInfoDTO> workOrderList = workOrderInfoService.selectByCustomerId(customerId);
        
        log.info("根据客户ID查询工单信息完成，客户ID: {}，查询到 {} 条记录", customerId, workOrderList.size());
        return new Result<>(workOrderList);
    }

    @ApiOperation(value = "修改工单信息", notes = "修改工单信息")
    @PostMapping("/update")
    public Result update(@RequestBody WorkOrderInfoSaveBO saveBO) {
        log.info("开始更新工单信息，请求参数: {}", saveBO);
        
        if (saveBO.getId() == null) {
            log.warn("更新工单信息失败，ID为空");
            return new Result<>(CodeEnum.FAIL_100002);
        }
        
        // 检查工单是否存在
        WorkOrderInfoDTO existing = workOrderInfoService.selectById(saveBO.getId());
        if (existing == null) {
            log.warn("更新工单信息失败，工单不存在，ID: {}", saveBO.getId());
            return new Result<>(CodeEnum.FAIL_100003);
        }
        
        WorkOrderInfoDTO dto = new WorkOrderInfoDTO();
        BeanUtils.copyProperties(saveBO, dto);
        dto.setId(saveBO.getId());
        // 设置更新时间
        dto.setUpdateTime(new Date());
        
        log.info("准备更新工单信息: {}", dto);
        boolean flag = workOrderInfoService.updateById(dto);
        
        if (flag) {
            log.info("工单信息更新成功，ID: {}", saveBO.getId());
            return new Result<>();
        } else {
            log.error("工单信息更新失败，ID: {}", saveBO.getId());
            return new Result<>(CodeEnum.FAIL_100008);
        }
    }

    @ApiOperation(value = "删除工单信息",notes = "删除工单信息")
    @ApiImplicitParam(name = "id",value = "工单信息id",required = true,paramType = "query",dataType = "Long")
    @PostMapping("/delete")
    public Result delete(@RequestParam("id") Long id){
        boolean flag = workOrderInfoService.deleteById(id);
        if (flag){
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL_100009);
        }
    }

    @ApiOperation(value = "添加工单信息", notes = "添加工单信息")
    @PostMapping("/add")
    public Result add(@RequestBody WorkOrderInfoSaveBO saveBO) {
        log.info("开始添加工单信息，请求参数: {}", saveBO);
        boolean flag = workOrderInfoService.add(saveBO);
        if (flag) {
            log.info("添加工单信息成功");
            return new Result<>();
        } else {
            log.error("添加工单信息失败");
            return new Result<>(CodeEnum.FAIL_100007);
        }
    }

    /**
     * 分配订单给接单员
     * @param id 订单ID
     * @param dispatcherId 调度员ID
     * @param employeeId 接单员ID
     * @return 分配结果
     */
    @PostMapping("/assign")
    @ApiOperation(value = "分配订单给接单员", notes = "分配订单给接单员")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "订单ID", required = true, paramType = "query", dataType = "Long"),
            @ApiImplicitParam(name = "dispatcherId", value = "调度员ID", required = true, paramType = "query", dataType = "Long"),
            @ApiImplicitParam(name = "employeeId", value = "接单员ID", required = true, paramType = "query", dataType = "Long")
    })
    public Result assignOrder(@RequestParam("id") Long id,
                              @RequestParam("dispatcherId") Long dispatcherId,
                              @RequestParam("employeeId") Long employeeId) {
        WorkOrderInfoDTO dto = new WorkOrderInfoDTO();
        dto.setId(id);
        dto.setDispatcherId(dispatcherId);
        dto.setEmployeeId(employeeId);
        dto.setStatus(1); // 设置为处理中状态
        dto.setUpdateTime(new Date()); // 添加更新时间

        boolean flag = workOrderInfoService.updateById(dto);
        if (flag) {
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL_100008);
        }
    }


    /**
     * 根据订单标题搜索工单信息
     * @param title 订单标题
     * @return 工单信息列表
     */
    @PostMapping("/getByTitle")
    @ApiOperation(value = "根据订单标题搜索", notes = "根据订单标题搜索工单信息")
    @ApiImplicitParam(name = "title", value = "订单标题", required = true, paramType = "query", dataType = "String")
    public Result<List<WorkOrderInfoDTO>> getByTitle(@RequestParam("title") String title) {
        if (title == null || title.trim().isEmpty()) {
            return new Result<>(CodeEnum.FAIL_100002);
        }

        Wrapper<WorkOrderInfoDTO> wrapper = new EntityWrapper<>();
        wrapper.like("title", title);
        List<WorkOrderInfoDTO> workOrderList = workOrderInfoService.selectList(wrapper);

        return new Result<>(workOrderList);
    }


    /**
     * 取消订单
     * @param id 订单ID
     * @return 取消结果
     */
    @PostMapping("/cancel")
    @ApiOperation(value = "取消订单", notes = "取消订单")
    @ApiImplicitParam(name = "id", value = "订单ID", required = true, paramType = "query", dataType = "Long")
    public Result cancelOrder(@RequestParam("id") Long id) {
        log.info("开始取消订单，订单ID: {}", id);
        
        if (id == null) {
            log.warn("取消订单失败，订单ID为空");
            return new Result<>(CodeEnum.FAIL_100002);
        }
        
        // 检查工单是否存在
        WorkOrderInfoDTO existing = workOrderInfoService.selectById(id);
        if (existing == null) {
            log.warn("取消订单失败，工单不存在，ID: {}", id);
            return new Result<>(CodeEnum.FAIL_100003);
        }
        
        // 检查工单当前状态是否允许取消
        Integer currentStatus = existing.getStatus();
        if (currentStatus == 3) {
            log.warn("取消订单失败，工单已处于取消状态，ID: {}", id);
            return new Result<>(CodeEnum.FAIL_100002.getCode(), "工单已处于取消状态");
        }
        
        // 更新工单状态为已取消(3)
        WorkOrderInfoDTO dto = new WorkOrderInfoDTO();
        dto.setId(id);
        dto.setStatus(3); // 设置为已取消状态
        dto.setUpdateTime(new Date()); // 更新时间
        
        boolean flag = workOrderInfoService.updateById(dto);
        if (flag) {
            log.info("订单取消成功，ID: {}", id);
            return new Result<>();
        } else {
            log.error("订单取消失败，ID: {}", id);
            return new Result<>(CodeEnum.FAIL_100008);
        }
    }

    /**
     * 完成订单
     * @param completeBO 完成信息
     * @return 完成结果
     */
    @PostMapping("/complete")
    @ApiOperation(value = "完成订单", notes = "完成订单")
    public Result completeOrder(@RequestBody WorkOrderCompleteBO completeBO) {
        log.info("开始完成订单，订单ID: {}", completeBO.getOrderId());

        Long id = completeBO.getOrderId();
        if (id == null) {
            log.warn("完成订单失败，订单ID为空");
            return new Result<>(CodeEnum.FAIL_100002);
        }

        // 检查工单是否存在
        WorkOrderInfoDTO existing = workOrderInfoService.selectById(id);
        if (existing == null) {
            log.warn("完成订单失败，工单不存在，ID: {}", id);
            return new Result<>(CodeEnum.FAIL_100003);
        }

        // 检查工单当前状态是否允许完成
        Integer currentStatus = existing.getStatus();
        if (currentStatus == 2) {
            log.warn("完成订单失败，工单已处于完成状态，ID: {}", id);
            return new Result<>(CodeEnum.FAIL_100002.getCode(), "工单已处于完成状态");
        }

        if (currentStatus == 3) {
            log.warn("完成订单失败，工单已处于取消状态，ID: {}", id);
            return new Result<>(CodeEnum.FAIL_100002.getCode(), "工单已处于取消状态");
        }

        // 更新工单状态为已完成(2)，并设置订单价格、服务费
        WorkOrderInfoDTO dto = new WorkOrderInfoDTO();
        dto.setId(id);
        dto.setStatus(2); // 设置为已完成状态
        dto.setPay(completeBO.getPay()); // 设置订单价格
        dto.setServicePay(completeBO.getServicePay()); // 设置服务费
        dto.setUpdateTime(new Date()); // 更新时间

        boolean flag = workOrderInfoService.updateById(dto);
        if (flag) {
            log.info("订单完成成功，ID: {}", id);
            return new Result<>();
        } else {
            log.error("订单完成失败，ID: {}", id);
            return new Result<>(CodeEnum.FAIL_100008);
        }
    }
    
    /**
     * 获取员工未完成订单数量
     * @param employeeId 员工ID
     * @return 未完成订单数量
     */
    @PostMapping("/getUnfinishedOrderCount")
    @ApiOperation(value = "获取员工未完成订单数量", notes = "获取指定员工未完成（状态为0待分配或1处理中）的订单数量")
    @ApiImplicitParam(name = "employeeId", value = "员工ID", required = true, paramType = "query", dataType = "Long")
    public Result<Integer> getUnfinishedOrderCount(@RequestParam("employeeId") Long employeeId) {
        log.info("开始获取员工未完成订单数量，员工ID: {}", employeeId);
        
        if (employeeId == null) {
            log.warn("获取员工未完成订单数量失败，员工ID为空");
            return new Result<>(CodeEnum.FAIL_100002);
        }
        
        int count = workOrderInfoService.countUnfinishedOrdersByEmployeeId(employeeId);
        
        log.info("获取员工未完成订单数量完成，员工ID: {}，未完成订单数量: {}", employeeId, count);
        return new Result<>(count);
    }
    
    /**
     * 获取所有员工的未完成订单数量
     * @return 员工ID和未完成订单数量的映射
     */
    @PostMapping("/getAll")
    @ApiOperation(value = "获取所有员工未完成订单数量", notes = "获取所有员工未完成（状态为0待分配或1处理中）的订单数量")
    public Result<Map<Long, Integer>> getAllEmployeesUnfinishedOrderCount() {
        log.info("开始获取所有员工未完成订单数量");
        
        Map<Long, Integer> employeeUnfinishedOrders = workOrderInfoService.countAllEmployeesUnfinishedOrders();
        
        log.info("获取所有员工未完成订单数量完成，共 {} 个员工", employeeUnfinishedOrders.size());
        return new Result<>(employeeUnfinishedOrders);
    }

}